package mts;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

import org.apache.log4j.Logger;

public class ElevatorControllerInternalConnectionServer extends Thread {

	private static final Logger log = Logger.getLogger(ElevatorControllerInternalConnectionServer.class);
	
	private ServerSocket serverSocket;
	private ProjectControllerManager manager;
	private HashMap<Byte, ElevatorControllerInternalConnection> elevatorControllerInternalConnections = new HashMap<Byte,ElevatorControllerInternalConnection>();
	
	public ElevatorControllerInternalConnection getElevatorControllerInternalConnection(byte car) {
		return elevatorControllerInternalConnections.get(car);
	}
	
	public ElevatorControllerInternalConnectionServer(int serverPort, ProjectControllerManager gui) {
		this.manager = gui;
		try {
			serverSocket = new ServerSocket(serverPort);
			log.info("Server initalized on " + InetAddress.getLocalHost() + ":" + serverPort);
		} catch (IOException ex) {
			log.error("Could not create Receive Server Socket.", ex);
			
			System.exit(1);
		}
	}
	
	@Override
	public void run() {
		receiveConnections();
	}
	
	private void receiveConnections() {
		while (true) {
			try {
				Socket clientSocket = serverSocket.accept();
				ElevatorControllerInternalConnection elevatorControllerInternalConnection = new ElevatorControllerInternalConnection(manager, clientSocket);
				elevatorControllerInternalConnections.put(elevatorControllerInternalConnection.getCar(), elevatorControllerInternalConnection);							
				
			} catch (IOException ex) {
				log.error("Error accepting connection from client.", ex);
			}				
		}		
	}
	
	
}
